package com.ky.pro.java.nio.http.server.router.impl;

import com.ky.pro.java.nio.http.server.router.IGatewayRouterRule;
import org.apache.commons.lang3.RandomUtils;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @ClassName RandomRouterRule
 * @Description TODO
 * @Date 2021/11/20 17:10
 * @Author kevin
 **/
public class RandomRouterRule implements IGatewayRouterRule {

    @Override
    public InetSocketAddress findServers(LinkedHashSet<InetSocketAddress> addressSet) {

        if (addressSet != null && !addressSet.isEmpty()) {
            int serverCnt = addressSet.size();
            int idx = RandomUtils.nextInt(0, serverCnt);
            List<InetSocketAddress> addressList = new ArrayList<>(addressSet);
            return addressList.get(idx);
        }

        return null;
    }
}
